/*
 * @Author: zi.yang
 * @Date: 2022-02-07 10:29:06
 * @LastEditors: zi.yang
 * @LastEditTime: 2022-02-08 23:08:56
 * @Description: In User Settings Edit
 * @FilePath: \api-generator\app\service\home.js
 */
'use strict';

const { default: axios } = require('axios');
const { Service } = require('egg');
const AjaxResponse = require('../utils/AjaxResponse');
const fs = require('fs');
const generatorPostmanDoc = require('../utils/toPostman');
const dayjs = require('dayjs');

class HomeService extends Service {
  async getSwaggerDoc({ swaggerUrl }) {
    const url = swaggerUrl.trim();
    if (!url) {
      return AjaxResponse.error({ code: 403, msg: 'swagger 文档路径不能为空！' });
    }
    const isHttp = /^https?:\/\//.test(url);
    const apiUrl = isHttp ? url : 'http://' + url;
    // 请求 swagger api
    const result = await axios.get(apiUrl).then(res => {
      return AjaxResponse.success({ data: res.data });
    }).catch(error => {
      return AjaxResponse.error({ error });
    });
    return result;
  }

  async generateToPostman({ swaggerUrl }) {
    const result = await this.getSwaggerDoc({ swaggerUrl });
    if (!result.success) return result;
    const postman = generatorPostmanDoc(result.data);
    // 生成唯一文件名
    const date = dayjs().format('YYYYMMDDHHmmssSSS');
    const random = (Math.random() * 100000).toFixed(0);
    const filename = date + '-' + random + '.json';
    // 文件路径
    const filepath = this.ctx.uploadPath + '/' + filename;
    const data = Buffer.from(JSON.stringify(postman));
    fs.writeFileSync(filepath, data);
    const userId = this.ctx.user._id;
    const fileInfo = {
      filename,
      filepath,
      create_by: userId,
    };
    return await this.service.file.add(fileInfo);
  }
}
module.exports = HomeService;
